<template>
  <van-nav-bar
      title="添加设备"
      fixed
  />
  <div class="main">
    <van-form @submit="onSubmit">
      <van-cell-group inset>
        <van-field
            v-model="form.DeviceName"
            name="DeviceName"
            label="设备名称"
            placeholder="支持英文字母、数字"
            :rules="[{ required: true, message: '请填写用设备名称' },{message:'仅支持英文字母、数字',validator:validator},{message:'至少4个字符长度',validator:min}]"
        />
        <van-field
            v-model="form.Nickname"
            name="Nickname"
            label="备注"
            placeholder="备注"
            :rules="[{ required: true, message: '请填写备注' },{message:'至少4个字符长度',validator:min}]"
        />
      </van-cell-group>
      <div style="margin: 16px;">
        <van-button round block type="primary" native-type="submit">
          提交
        </van-button>
      </div>
    </van-form>
  </div>
</template>
<script setup>
import {reactive} from "vue";
import {showToast} from "vant";
import {iotAdd} from '@/api';

import {useRouter} from "vue-router";

const router = useRouter()

const validator = (val) => {
  return /^[a-zA-Z0-9]+$/.test(val)
}
const form = reactive({
  DeviceName: '',
  Nickname: '',
})

const onSubmit = (value) => {
  iotAdd(value).then(res => {
    showToast({
      message: res.message,
      duration:1000,
    })
    if (res.code === 200) {
      setTimeout(() => {
        router.push('/iot')
      },2000)
    }
  })
}
const min = (v)=>{
  return v.length >=4
}
</script>
<style scoped>
.main {
  padding-top: 60px;
}
</style>